import { Component, Injector, ViewChild } from '@angular/core';
import { IBasicOrganizationUnitInfo } from '@app/admin/organization-units/basic-organization-unit-info';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { LazyLoadEvent, SelectItem, TreeNode } from 'primeng/api';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';
import { finalize } from 'rxjs/operators';
import { PQualitWorkStepDto, QualityPlatformServiceProxy, CommonServiceProxy } from '@shared/service-proxies/service-proxies';
import { result } from 'lodash';
import { MessageService } from 'abp-ng2-module/dist/src/message/message.service';
import { LookPathComponent } from '../components/look-path/look-path.component';
import { FileDownloadService } from '@shared/utils/file-download.service';
import { Paginator } from 'primeng/components/paginator/paginator';

@Component({
    templateUrl: './qualitydataquery.component.html',
    styleUrls: ['./qualitydataquery.component.less'],
    animations: [appModuleAnimation()]
})
export class QualitydataqueryComponent extends AppComponentBase {
    @ViewChild('path') lookPath: LookPathComponent;
    @ViewChild('paginator') paginator: Paginator;
    selectedOu: TreeNode;
    userform: FormGroup;//右侧form
    genders: any;//表名查询下啦
    //模型下拉数据
    Models = []
    //搜索时的model值
    modelValue = undefined
    //发次下拉数据
    LotNoList = []
    selectedFiles: TreeNode
    //发次值
    lotNo = undefined
    loadingtree: boolean
    //树数据
    treeData = [];
    FisrtDrawingNum: undefined;//图号
    SecondDrawingNum: undefined;//零件编号
    RecordElementStr: undefined;// 记录项目
    ToolUsed: undefined;//所用工具编号
    workStepData: {};//工步动态表List
    workStepHeader: any;//工步动态表Header
    tablemodel = undefined//表结构v-model
    tabvalue = undefined//tab切换数组下标
    //点击的树节点信息
    checkedTree: any;
    //右侧表格行数据
    rowData: any;
    //右侧动态表信息
    workstepInfo: any;
    // 图片视频
    photoObj: any;
    constructor(
        injector: Injector,
        private _qualityPlatform: QualityPlatformServiceProxy,
        private _fileDownloadService: FileDownloadService,
        private _commonServiceProxy: CommonServiceProxy,
        private _messageService: MessageService
    ) {
        super(injector);

    }
    getUser(item) {
        let msg = item ? item.split('，') : [];
        // let result = [];
        // for (const i of msg) {
        //     let data = i.split('_');
        //     result.push(data);
        // }
        let rs = [];
        for (const item of msg) {
            let msg = item.split('*');
            let data = { name: undefined, time: undefined, url: undefined };
            data.name = msg[0];
            data.time = msg[1];
            data.url = msg[2];
            rs.push(data);
        }
        return rs;
    }
    //点击路径显示弹窗
    showUrlInfo(row) {
        this.rowData = row
        let that = this
        if (this.rowData && this.rowData.rWorkStepEntityId) {
            setTimeout(() => {
                that.lookPath.show()
            }, 20)
        } else {
            this._messageService.info('暂无数据！')
        }
    }
    //导出
    exportToExcel(): void {
        if (!Boolean(this.modelValue && this.lotNo)) {
            this._messageService.warn('请先选择型号和发次!')
            return
        }
        if (!Boolean(this.checkedTree)) {
            this._messageService.warn('请先选择树节点!')
            return
        }
        abp.ui.setBusy();
        this._qualityPlatform.exportReportExcel(
            this.modelValue, this.lotNo, this.checkedTree ? this.checkedTree.id : '',
            this.tablemodel, '', '', '', '', '', '', this.checkedTree.key != -1 ? false : true,
            this.checkedTree.nodeLevel, false, [], true)
            .subscribe(result => {
                abp.ui.clearBusy();
                // this._fileDownloadService.downloadTempFile(result);
                window.open(result);
                URL.revokeObjectURL(result);
            });
    }
    export(): void {
        if (!Boolean(this.modelValue && this.lotNo)) {
            this._messageService.warn('请先选择型号和发次!')
            return
        }
        if (!Boolean(this.checkedTree)) {
            this._messageService.warn('请先选择树节点!')
            return
        }
        abp.ui.setBusy();
        this._qualityPlatform.exportReportExcel(
            this.modelValue, this.lotNo, this.checkedTree ? this.checkedTree.id : '',
            this.tablemodel, '', '', '', '', '', '', this.checkedTree.key != -1 ? false : true,
            this.checkedTree.nodeLevel, false, [], false)
            .subscribe(result => {
                abp.ui.clearBusy();
                // this._fileDownloadService.downloadTempFile(result);
                window.open(result);
                URL.revokeObjectURL(result);
            });
    }
    //获取表名
    getTableName(id, level, isShow) {
        this._qualityPlatform.getHeaderList(this.modelValue, this.lotNo, id, level, isShow, undefined)
            .pipe(finalize(() => { })).subscribe(result => {
                this.genders = [];
                result.forEach(item => {
                    this.genders.push({
                        label: item,
                        value: item
                    })
                })
            })
    }
    //处理图片
    // getImage(item) {
    //     let imageList = item ? item.split(',') : [];
    //     let result = []
    //     imageList.forEach((e, i) => {
    //         if (e.includes('.mp4')) {
    //         } else {
    //             // let a = e.split('_');
    //             // a[a.length - 1] = a[a.length - 1].replace('thumbnail', '');
    //             // let rs = a.join('');
    //             // result.push({
    //             //     source: rs,
    //             //     thumbnail: rs,
    //             //     title: ''
    //             // })
    //             result.push({
    //                     source: e,
    //                     thumbnail: e,
    //                     title: ''
    //                 })
    //         }
    //     })
    //     return result;
    // }
    getImages(item) {
        let imageList = item ? item.split(',') : [];
        let result = []
        imageList.forEach((e, i) => {
            if (e.includes('.mp4')) {
            } else {
                let a = e.split('_');
                a[a.length - 1] = a[a.length - 1].replace('thumbnail', '');
                let rs = a.join('');
                result.push({
                    source: rs,
                    thumbnail: rs,
                    title: ''
                })
            }
        })
        return result;
    }
    getImagesNew(item) {
        let imageList = item ? item.split(',') : [];
        let result = []
        imageList.forEach((e, i) => {
            if (e.includes('.mp4')) {
            } else {
                // let a = e.split('_');
                // a[a.length - 1] = a[a.length - 1].replace('thumbnail', '');
                // let rs = a.join('');
                let rs = e.replace('_thumbnail', '');
                result.push({
                    source: rs,
                    thumbnail: rs,
                    title: ''
                })
            }
        })
        return result;
    }
    getVideo(item) {
        let imageList = item ? item.split(',') : []
        let result = []
        imageList.forEach((e, i) => {
            if (e.includes('.mp4')) {
                result.push({
                    source: e,
                    thumbnail: e,
                    title: ''
                })
            }
        })
        return result
    }
    //根据表名搜索
    searchRight() {
        let that = this;
        if (!Boolean(that.modelValue && that.lotNo)) {
            that._messageService.warn('请先选择型号和发次!')
            return
        }
        if (!Boolean(this.checkedTree)) {
            this._messageService.warn('请先选择树节点!')
            return
        }
        abp.ui.setBusy(undefined, '', 1);
        /// <param name="model">型号</param>
        /// <param name="lotstr">发次</param>
        /// <param name="nodeId">节点Id</param>
        /// <param name="tableNameStr">多表名称 以逗号隔开</param>
        /// <param name="FisrtDrawingNum">图号/代号</param>
        /// <param name="FirstDrawingName">图号名称</param>
        /// <param name="SecondDrawingNum">零件2代号</param>
        /// <param name="SecondDrawingName">零件2名称</param>
        /// <param name="ToolUsed">所用工具编号</param>
        /// <param name="RecordElementStr">记录项目</param>
        /// <param name="ShowAll">node节点是否为空 true则 无需选中节点</param>
        /// <param name="DisplayRoute">是否显示路径 true显示 </param>
        /// <param name="nodeLevel">节点层级 默认是节点 8为工序 9 为工步</param>
        /// <param name="reachTable">刷新分页的当前表名</param>
        /// <param name="envelope">是否包络，true 包络</param>
        /// <param name="pageIndex">查询的页数 </param>
        /// <param name="pageSize">每页显示的个数</param>
        /// <param name="paging">是否开启分页 默认为true分页,false不开启分页</param>
        that._qualityPlatform.statisticalReport(that.modelValue, that.lotNo,
            that.checkedTree ? that.checkedTree.id : undefined, that.tablemodel,
            that.FisrtDrawingNum, '', that.SecondDrawingNum, '', that.ToolUsed,
            that.RecordElementStr, this.checkedTree.key != -1 ? false : true, true,
            this.checkedTree ? this.checkedTree.nodeLevel : undefined,
            this.workStepHeader ? this.workStepHeader.tableName : undefined, false,
            that.paginator ? that.paginator.getPage() + 1 : 1, that.paginator ? that.paginator._rows : 10,
            true, [], undefined, false,true)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.workstepInfo = result;
                abp.ui.clearBusy();
                this.onTabChange({ index: 0 });
            });
            this._qualityPlatform.getPictureAndVideoNums(this.modelValue, this.lotNo,
                this.checkedTree ? this.checkedTree.id : undefined, this.tablemodel,
                this.FisrtDrawingNum, '', this.SecondDrawingNum, '', this.ToolUsed,
                this.RecordElementStr, this.checkedTree.key != -1 ? false : true,
                this.checkedTree ? this.checkedTree.nodeLevel : undefined,[], )
            .pipe(finalize(() => { this.loadingtree = false; }))
            .subscribe(result => {
                console.log(result);
                this.photoObj =result;
            });
    }
    //tab 切换工步动态表
    onTabChange(event) {

        //如果当前点击的tab不是已选中的tab 重置页码
        if (event.index != this.tabvalue && this.paginator) {
            this.paginator._first = 0;
            this.paginator._rows = 10;
        }
        if (this.workstepInfo.tableNameDictionary[event.index] != undefined) {
            this.tabvalue = event.index;
            this.workStepHeader = this.workstepInfo.tableNameDictionary[event.index];
            this.workStepData = this.workstepInfo.workStepOut[this.workstepInfo.tableNameDictionary[event.index].tableKey];
        } else {
            this.workStepHeader = [];
            this.workStepData = null;
        }

    }
    //树搜索
    treeSearch() {
        if (!Boolean(this.modelValue && this.lotNo)) {
            this._messageService.warn('请先选择型号和发次!')
            return
        }

        this._qualityPlatform.getTreeContainRoot(this.lotNo, this.modelValue)
            .pipe(finalize(() => { })).subscribe(result => {
                this.treeData = [];
                this.treeData.push({
                    ...result.parentNode,
                    key: -1,
                    nodeDrawingNo: result.parentNode.drawingNo,
                    nodeName: result.parentNode.modelName,
                    model: result.parentNode.model,
                    lotNo: result.parentNode.lotNo,
                    stageSign: result.parentNode.stageSign,
                    children: result.childNodes
                })
                this.expandAll();
            })
    }
    //点击树节点事件
    nodeSelect(event) {
        this.checkedTree = event.node
        if (this.checkedTree.parent == undefined) {
            this.getTableName(this.checkedTree.id, this.checkedTree.nodeLevel, true);
        } else {
            this.getTableName(this.checkedTree.id, this.checkedTree.nodeLevel, false);
        }
        //已关联查询工序及工步树
        if (this.checkedTree.isRelation == 1) {
            this.loadingtree = true
            this._qualityPlatform.getQualityWorkStepList(this.checkedTree.id)
                .pipe(finalize(() => { this.loadingtree = false; }))
                .subscribe(result => {
                    let rowInfo = this.getTreeRecursion(this.treeData, this.checkedTree.id);
                    rowInfo.children = result;
                });
        }
    }
    // 递归循环树级结构 获取对象 通过物料ID 递归
    getTreeRecursion(data, current) {
        var result = null;
        if (!data) {
            // return; 中断执行
            return;
        }
        for (var i in data) {
            if (result != null) {
                break;
            }
            var item = data[i];
            // 通过id找到树结构相应节点 找到则跳出
            if (item.id == current) {
                result = item;
                break;
            } else if (item.children && item.children.length > 0) {
                result = this.getTreeRecursion(item.children, current);
            }
        }
        return result;
    }
    //树全部展开
    expandAll() {
        this.treeData.forEach((node) => {
            this.expandRecursive(node, true);
        });
    }
    ngOnInit() {
        //获取型号下拉
        this.Models = [
            {
                label: '请选择',
                value: undefined
            }
        ];
        this._qualityPlatform.getModelNameList(undefined)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                for (const item of result) {
                    let data = { label: undefined, value: undefined };
                    data.label = item;
                    data.value = item;
                    this.Models.push(data);
                }
            });
    }
    onChange(event) {
        //获取发次
        this.LotNoList = [
            {
                label: '请选择',
                value: undefined
            }
        ];
        this._qualityPlatform.getLotNoList(undefined, this.modelValue)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                for (const item of result) {
                    let data = { label: undefined, value: undefined };
                    data.label = item;
                    data.value = item;
                    this.LotNoList.push(data);
                }
            });
    }
    private expandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.expandRecursive(childNode, isExpand);
            });
        }
    }


}
